package com.itheima.filter;

import com.itheima.utnil.CurrentHolder;
import com.itheima.utnil.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.Map;

//过滤层
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }


    @Override

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        1、为了获取客户端数据，以及响应客户端数据，将ServLetRequest转成HttpServLetRequest，将S
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
//        1/2、获取请求路径
        String url =request.getRequestURL().toString();
//3、判断路径是否需要拦截
        if (url.contains("/login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }


//        114、获取请求头令牌
        String token = request.getHeader("token");



//        1/5、令牌校验
        if (ObjectUtils.isEmpty(token)|| JwtUtils.parseJwt(token)==null){

//            1/6、校验通过，放行请求
            response.setStatus(401);
            return;
        }
//         获取令牌Id（不属于过滤器，额外添加）
//        解析令牌并存到集合里
        Map<String, Object> map = JwtUtils.parseJwt(token);
//        强转一次
        Integer id = (Integer) map.get("id");
        CurrentHolder.setCurrentId(id);


            filterChain.doFilter(servletRequest, servletResponse);
//         用完移除
        CurrentHolder.remove();


    }



    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
